package com.logica.hackthon.xmpp;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.flca.frw.log.ILog;
import com.flca.frw.log.LogHelper;
import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.MessageType;
import com.google.appengine.api.xmpp.Presence;
import com.google.appengine.api.xmpp.SendResponse;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;

@SuppressWarnings("serial")
public class XmppReceiverServlet extends HttpServlet {

	private XMPPService xmppService;

	private static ILog logger = LogHelper.getLogger(XmppReceiverServlet.class);

	@Override
	public void init() {
		this.xmppService = XMPPServiceFactory.getXMPPService();
	}

	// For testing. Real requests are POST
	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws IOException {
		logInfo("inside XmppReceiverServlet.doGet()");

		Message message = new MessageBuilder()
				.withMessageType(MessageType.CHAT).withFromJid(
						new JID(req.getParameter("from"))).withRecipientJids(
						new JID(req.getParameter("to"))).withBody(
						req.getParameter("body")).build();

		logInfo(message.toString());

		processMessage(message, res);
	}

	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws IOException {
		processMessage(xmppService.parseMessage(req), res);
	}

	public void processMessage(Message message, HttpServletResponse res)	throws IOException 
	{
		JID fromId = message.getFromJid();
		Presence presence = xmppService.getPresence(fromId);
		String presenceString = presence.isAvailable() ? "" : "not ";
		SendResponse response = xmppService.sendMessage(new MessageBuilder()
				.withBody(
						message.getBody() + " (you are " + presenceString
								+ "available)").withRecipientJids(fromId)
				.build());

		for (Map.Entry<JID, SendResponse.Status> entry : response.getStatusMap().entrySet()) {
			System.out.println("entry = " + entry);
			res.getWriter().println(	entry.getKey() + "," + entry.getValue() + "<br>");
		}

		sendTheXmmpMessage(fromId, "ok this works");
		
		res.getWriter().println("processed");
	}

	private void logInfo(String msg) {
		logger.info(msg);
		System.out.println(msg);
	}

	private void sendTheXmmpMessage(JID fromJid, String replyBody) 
	{
		String msgBody = "You sent me : " + replyBody;
		Message replyMessage = new MessageBuilder().withRecipientJids(fromJid)
				.withBody(msgBody).build();

		boolean messageSent = false;
		if (xmppService.getPresence(fromJid).isAvailable()) {
			SendResponse status = xmppService.sendMessage(replyMessage);
			messageSent = (status.getStatusMap().get(fromJid) == SendResponse.Status.SUCCESS);
		}
	}
}